<template>
  <!-- 经营类目选择弹框 -->
  <uni-popup ref="categoryPopup" type="bottom">
    <view class="category-picker-modal">
      <view class="picker-header">
        <text class="picker-cancel" @click="close">取消</text>
        <text class="picker-title">选择经营类目</text>
        <text class="picker-confirm" @click="confirmCategory">确认</text>
      </view>

      <!-- 加载状态 -->
      <view v-if="loading" class="loading-container">
        <uni-icons
          type="spinner-cycle"
          size="40"
          color="#ffbb00"
          class="loading-icon"
        />
        <text class="loading-text">加载中...</text>
      </view>

      <!-- 类目列表 -->
      <scroll-view
        v-else
        class="category-list"
        scroll-y
        @scrolltolower="loadMore"
        :lower-threshold="100"
      >
        <view
          v-for="item in categories"
          :key="item.id"
          class="category-item"
          :class="{ active: tempSelectedCategory?.id === item.id }"
          @click="selectItem(item)"
        >
          <text class="category-name">{{ item.name }}</text>
          <uni-icons
            v-if="tempSelectedCategory?.id === item.id"
            type="checkmarkempty"
            size="20"
            color="#ffbb00"
          />
        </view>

        <!-- 加载更多 -->
        <view v-if="loadingMore" class="loading-more">
          <uni-icons
            type="spinner-cycle"
            size="20"
            color="#999"
            class="loading-icon"
          />
          <text class="loading-more-text">加载更多...</text>
        </view>

        <!-- 没有更多 -->
        <view v-if="!hasMore && categories.length > 0" class="no-more">
          <text class="no-more-text">没有更多了</text>
        </view>

        <!-- 空状态 -->
        <view v-if="!loading && categories.length === 0" class="empty-state">
          <text class="empty-text">暂无经营类目</text>
        </view>
      </scroll-view>
    </view>
  </uni-popup>
</template>

<script setup>
import { ref } from "vue";
import { useRequest } from "ahooks-vue";
import { getBusinessCircleCategory } from "@/api/user";

const emit = defineEmits(["confirm"]);

// 弹框引用
const categoryPopup = ref(null);

// 类目列表
const categories = ref([]);

// 当前选中的类目
const selectedCategory = ref(null);

// 临时选中的类目（确认前）
const tempSelectedCategory = ref(null);

// 分页参数
const currentPage = ref(1);
const pageSize = ref(10);
const hasMore = ref(true);
const loadingMore = ref(false);

// 获取类目列表
const { loading, run: fetchCategories } = useRequest(
  (params) => getBusinessCircleCategory(params),
  {
    manual: true,
    onSuccess: (response) => {
      console.log("类目数据：", response);
      // 后端返回格式: { code: 2000, data: { total: 2, rows: [...] }, message: '' }
      const data = response.data;
      if (data && data.rows && Array.isArray(data.rows)) {
        const newItems = data.rows.map((item) => ({
          id: item.id,
          name: item.classifyName,
          logo: item.classifyLogo,
        }));

        console.log(
          `第${currentPage.value}页加载了${newItems.length}条数据，总数：${data.total}`
        );

        // 如果是第一页，直接赋值；否则追加
        if (currentPage.value === 1) {
          categories.value = newItems;
        } else {
          categories.value = [...categories.value, ...newItems];
        }

        // 判断是否还有更多数据（已加载数量 < 总数）
        const totalLoaded = categories.value.length;
        hasMore.value = totalLoaded < data.total;

        console.log(`已加载：${totalLoaded}条，是否还有更多：${hasMore.value}`);
      } else {
        hasMore.value = false;
      }

      loadingMore.value = false;
    },
    onError: (error) => {
      console.error("获取类目失败：", error);
      loadingMore.value = false;
      uni.showToast({
        title: "获取类目失败",
        icon: "none",
      });
    },
  }
);

// 加载更多
const loadMore = () => {
  if (loadingMore.value || !hasMore.value || loading.value) {
    return;
  }

  loadingMore.value = true;
  currentPage.value++;

  fetchCategories({
    limit: pageSize.value,
    offset: currentPage.value,
  });
};

// 打开弹框
const open = (currentCategory) => {
  if (currentCategory) {
    selectedCategory.value = { ...currentCategory };
    tempSelectedCategory.value = { ...currentCategory };
  }

  // 重置分页状态并加载第一页
  currentPage.value = 1;
  hasMore.value = true;
  categories.value = [];

  fetchCategories({
    limit: pageSize.value,
    offset: 1,
  });

  categoryPopup.value?.open();
};

// 关闭弹框
const close = () => {
  // 取消时恢复之前的选择
  tempSelectedCategory.value = selectedCategory.value
    ? { ...selectedCategory.value }
    : null;
  categoryPopup.value?.close();
};

// 选择类目
const selectItem = (item) => {
  tempSelectedCategory.value = { ...item };
};

// 确认选择
const confirmCategory = () => {
  if (!tempSelectedCategory.value) {
    uni.showToast({
      title: "请选择经营类目",
      icon: "none",
    });
    return;
  }

  selectedCategory.value = { ...tempSelectedCategory.value };
  emit("confirm", selectedCategory.value);
  categoryPopup.value?.close();
};

// 对外暴露方法
defineExpose({ open, close });
</script>

<style scoped lang="scss">
.category-picker-modal {
  background: #fff;
  border-radius: 16rpx 16rpx 0 0;
  max-height: 80vh;
  display: flex;
  flex-direction: column;
}

.picker-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 32rpx;
  border-bottom: 1rpx solid #f5f5f5;
}

.picker-cancel,
.picker-confirm {
  font-size: 28rpx;
  color: #ffbb00;
}

.picker-title {
  font-size: 32rpx;
  color: #333;
  font-weight: 500;
}

// 加载状态
.loading-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 100rpx 0;
  gap: 20rpx;

  .loading-icon {
    animation: rotate 1s linear infinite;
  }

  .loading-text {
    font-size: 28rpx;
    color: #999;
  }

  @keyframes rotate {
    from {
      transform: rotate(0deg);
    }
    to {
      transform: rotate(360deg);
    }
  }
}

// 类目列表
.category-list {
  max-height: 600rpx;
  background-color: #fff;
}

.category-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 32rpx 40rpx;
  background-color: #fff;
  border-bottom: 1px solid #f0f0f0;
  transition: background-color 0.2s;

  &:active {
    background-color: #f8f8f8;
  }

  &.active {
    background-color: #fff;

    .category-name {
      color: #ffbb00;
      font-weight: 500;
    }
  }

  .category-name {
    font-size: 30rpx;
    color: #333;
    line-height: 42rpx;
    flex: 1;
  }
}

// 空状态
.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 100rpx 0;

  .empty-text {
    font-size: 28rpx;
    color: #999;
  }
}

// 加载更多
.loading-more {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 30rpx 0;
  gap: 12rpx;

  .loading-icon {
    animation: rotate 1s linear infinite;
  }

  .loading-more-text {
    font-size: 24rpx;
    color: #999;
  }
}

// 没有更多
.no-more {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 30rpx 0;

  .no-more-text {
    font-size: 24rpx;
    color: #999;
  }
}
</style>

